﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public class SerializeUtil
{      /// <summary>
       /// object 转 byte[]
       /// </summary>
       /// <param name="value"></param>
       /// <returns></returns>
    public static byte[] ObjectToByteArray(object value)
    {
        MemoryStream ms = new MemoryStream();//创建编码解码的内存流对象
        BinaryFormatter bw = new BinaryFormatter();//二进制流序列化对象
        bw.Serialize(ms, value);//将Obj对象序列化为二进制对象写入到内存流
        byte[] result = new byte[ms.Length];
        //将流数据拷贝到结果数组
        Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int)ms.Length);
        ms.Close();
        return result;
    }
    /// <summary>
    /// byte[] 转 object
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static object ByteArrayToObject(byte[] value)
    {
        MemoryStream ms = new MemoryStream(value);//创建编码解码的内存流对象，并将需要反序列化的数据写入其中
        BinaryFormatter bw = new BinaryFormatter();//二进制流序列化对象
        object result = bw.Deserialize(ms);//将byte数组反序列化为Object对象
        ms.Close();
        return result;
    }
}
